package com.service.sale;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletResponse;

import com.dao.supply.InfoMapper;
import com.dao.supply.SupplyMapper;
import com.model.external.sap.SapDeliveryOrderModel;
import com.model.supply.SupplyInfoModel;
import com.model.sys.SysUser;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.excel.EasyExcel;
import com.common.StringUtils;
import com.common.easyui.EasyuiUtils;
import com.common.http.HttpResult;
import com.common.http.HttpStatus;
import com.dao.sale.SaleDeliveryOrdersDao;
import com.model.sale.SaleDeliveryOrdersModel;
import com.common.model.Global;
import com.common.spring.SpringMvcUtils;

import org.springframework.util.CollectionUtils;

@Service
public class SaleDeliveryOrdersService {
	static final Logger logger = LoggerFactory.getLogger(SaleDeliveryOrdersService.class);

	@Autowired
	SaleDeliveryOrdersDao saleDeliveryOrdersDao;

	@Autowired
	InfoMapper infoMapper;

	/**
	 * 列表查询
	 *
	 * @param queryMap
	 * @return
	 */
	public HttpResult selectList(Map<String, Object> queryMap) {
		HttpResult httpResult = new HttpResult();
		EasyuiUtils.addPageNum(queryMap);
		EasyuiUtils.addFilter(queryMap);
		SysUser sysUser = SpringMvcUtils.getSysUser();
		if (!sysUser.getSuperadmin().equals(Global.YES + "")) {
			if (StringUtils.isNotNull(sysUser.getDatapermission())) {
				queryMap.put("deptIds", sysUser.getDatapermission().split(","));
			} else {
				queryMap.put("createId", sysUser.getUserid());
			}
		}
		List<SaleDeliveryOrdersModel> list = saleDeliveryOrdersDao.selectList(queryMap);
		int count = saleDeliveryOrdersDao.selectListCount(queryMap);
		httpResult.setRows(list);
		httpResult.setTotal(count);
		logger.info("selectList:{}", list);
		return httpResult;
	}

	/**
	 * 详情
	 *
	 * @param
	 * @return
	 */
	public HttpResult selectInfor(String deliId, String orderNo) {
		HttpResult httpResult = new HttpResult();
		SaleDeliveryOrdersModel saleDeliveryOrdersModel = saleDeliveryOrdersDao.load(deliId);
		httpResult.setData(saleDeliveryOrdersModel);
		httpResult.setCode(HttpStatus.SUCCESS_CODE);
		return httpResult;
	}

	/**
	 * 保存
	 *
	 * @param
	 * @return
	 */
	public HttpResult save(SaleDeliveryOrdersModel saleDeliveryOrdersModel) {
		if (saleDeliveryOrdersModel == null) {
			return HttpResult.error("参数不能为空");
		}
		HttpResult httpResult = new HttpResult();
		int result = 0;
		if (!StringUtils.isNotNull(saleDeliveryOrdersModel.getDeliId())) {
			saleDeliveryOrdersModel.setDeliId(UUID.randomUUID().toString());
			result = saleDeliveryOrdersDao.insert(saleDeliveryOrdersModel);
		} else {
			result = saleDeliveryOrdersDao.update(saleDeliveryOrdersModel);
		}
		if (result > 0) {
			httpResult.setMsg("保存成功!");
			httpResult.setData(saleDeliveryOrdersModel);
		} else {
			httpResult.setCode(HttpStatus.GLOBAL_EXCEPTION_CODE);
			httpResult.setMsg("保存失败!");
		}
		return httpResult;
	}

	/**
	 * 提交
	 *
	 * @param
	 * @return
	 */
	public HttpResult commit(SaleDeliveryOrdersModel saleDeliveryOrdersModel) {
		if (saleDeliveryOrdersModel == null) {
			return HttpResult.error("参数不能为空");
		}
		// saleDeliveryOrdersModel.setStatus(Global.YES+"");
		HttpResult httpResult = new HttpResult();
		int result = 0;
		result = saleDeliveryOrdersDao.update(saleDeliveryOrdersModel);
		if (result > 0) {
			httpResult.setMsg("保存成功!");
			httpResult.setData(saleDeliveryOrdersModel);
		} else {
			httpResult.setCode(HttpStatus.GLOBAL_EXCEPTION_CODE);
			httpResult.setMsg("保存失败!");
		}
		return httpResult;
	}

	/**
	 * 删除
	 *
	 * @param
	 * @return
	 */
	public HttpResult delete(String deliId, String orderNo) {
		if (!StringUtils.isNotNull(deliId) || !StringUtils.isNotNull(orderNo)) {
			return HttpResult.error("参数不能为空");
		}
		SaleDeliveryOrdersModel model = saleDeliveryOrdersDao.load(deliId);

		HttpResult httpResult = new HttpResult();
		int result = saleDeliveryOrdersDao.delete(deliId, orderNo);
		if (result > 0) {
			httpResult.setMsg("删除成功！");
		} else {
			httpResult.setCode(HttpStatus.GLOBAL_EXCEPTION_CODE);
			httpResult.setMsg("不存在此条数据！");
		}
		return httpResult;
	}

	/**
	 * 撤回
	 *
	 * @param
	 * @return
	 */
	public HttpResult back(String deliId, String orderNo) {
		if (!StringUtils.isNotNull(deliId) || !StringUtils.isNotNull(orderNo)) {
			return HttpResult.error("参数不能为空");
		}
		SaleDeliveryOrdersModel model = saleDeliveryOrdersDao.load(deliId);

		HttpResult httpResult = new HttpResult();

		int result = saleDeliveryOrdersDao.update(model);
		if (result > 0) {
			httpResult.setMsg("删除成功！");
		} else {
			httpResult.setCode(HttpStatus.GLOBAL_EXCEPTION_CODE);
			httpResult.setMsg("不存在此条数据！");
		}
		return httpResult;
	}

	/**
	 * 导出
	 *
	 * @param queryMap
	 * @param response
	 */
	public void export(Map<String, Object> queryMap, HttpServletResponse response) {
		List<SaleDeliveryOrdersModel> list = saleDeliveryOrdersDao.selectList(queryMap);
		logger.info("export:{}", list);
		try {
			EasyExcel.write(response.getOutputStream(), SaleDeliveryOrdersModel.class).sheet("模板").doWrite(list);
		} catch (IOException e) {
			logger.error("导出错误:{}", e.getMessage());
		}

	}

	public HttpResult transportDeliveryToCMP(List<SapDeliveryOrderModel> sapDeliveryOrderModels) {
		if (sapDeliveryOrderModels.size() > 1000) {
			return HttpResult.error("数据量超过1000条");
		}
		int result = 0;
		for (SapDeliveryOrderModel sapDeliveryOrderModel : sapDeliveryOrderModels) {
			if (StringUtils.isNullOrEmpty(sapDeliveryOrderModel.getVBELN_D())) {
				return HttpResult.error("交货单号不得为空");
			}
			String orderNo = sapDeliveryOrderModel.getVBELN_D();
			String status = "C".equals(sapDeliveryOrderModel.getZDN_FLAG()) ? "0" : "1";
			SaleDeliveryOrdersModel orderTemp = saleDeliveryOrdersDao.loadByOrderNo(orderNo);
			if (orderTemp == null) {
				orderTemp = new SaleDeliveryOrdersModel();
				orderTemp.setStatus(Global.NO + "");
				orderTemp.setDeliId(UUID.randomUUID().toString());
				// 交货单编号
				orderTemp.setOrderNo(orderNo);
				// 交货单类型
				orderTemp.setOrderType(
						!StringUtils.isNullOrEmpty(sapDeliveryOrderModel.getLFART()) ? sapDeliveryOrderModel.getLFART()
								: "");
				// 销售组织
				orderTemp.setVkorg(
						!StringUtils.isNullOrEmpty(sapDeliveryOrderModel.getVKORG()) ? sapDeliveryOrderModel.getVKORG()
								: "");
				// 类型描述
				orderTemp.setOrderTypeDesc(
						!StringUtils.isNullOrEmpty(sapDeliveryOrderModel.getVTEXT()) ? sapDeliveryOrderModel.getVTEXT()
								: "");
				// 客户编码
				orderTemp.setCustomerCode(
						!StringUtils.isNullOrEmpty(sapDeliveryOrderModel.getKUNAG()) ? sapDeliveryOrderModel.getKUNAG()
								: "");
				// 客户名称
				orderTemp.setCustomerName(
						!StringUtils.isNullOrEmpty(sapDeliveryOrderModel.getNAME1()) ? sapDeliveryOrderModel.getNAME1()
								: "");
				// 交货行项目号
				orderTemp.setDeliveryLineNo(!StringUtils.isNullOrEmpty(sapDeliveryOrderModel.getPOSNR_D())
						? sapDeliveryOrderModel.getPOSNR_D()
						: "");
				// 物料编码
				orderTemp.setMmCode(
						!StringUtils.isNullOrEmpty(sapDeliveryOrderModel.getMATNR()) ? sapDeliveryOrderModel.getMATNR()
								: "");
				// 物料描述
				orderTemp.setMmDesc(
						!StringUtils.isNullOrEmpty(sapDeliveryOrderModel.getMAKTX()) ? sapDeliveryOrderModel.getMAKTX()
								: "");
				// 物料组
				orderTemp.setMmGroup(
						!StringUtils.isNullOrEmpty(sapDeliveryOrderModel.getMATKL()) ? sapDeliveryOrderModel.getMATKL()
								: "");
				// 组描述
				orderTemp.setMmGroupDesc(
						!StringUtils.isNullOrEmpty(sapDeliveryOrderModel.getWGBEZ()) ? sapDeliveryOrderModel.getWGBEZ()
								: "");
				// 所属工厂
				orderTemp.setFactoryCode(
						!StringUtils.isNullOrEmpty(sapDeliveryOrderModel.getWERKS()) ? sapDeliveryOrderModel.getWERKS()
								: "");
				// 存储地点
				orderTemp.setStorage(
						!StringUtils.isNullOrEmpty(sapDeliveryOrderModel.getLGORT()) ? sapDeliveryOrderModel.getLGORT()
								: "");
				// 发货数量
				orderTemp.setDeliveryQuantity(
						!StringUtils.isNullOrEmpty(sapDeliveryOrderModel.getLFIMG()) ? sapDeliveryOrderModel.getLFIMG()
								: "0");
				// 发货单位
				orderTemp.setDeliveryUnit(
						!StringUtils.isNullOrEmpty(sapDeliveryOrderModel.getMEINS()) ? sapDeliveryOrderModel.getMEINS()
								: "");
				// 签收数量
				orderTemp.setSignQuantity(
						!StringUtils.isNullOrEmpty(sapDeliveryOrderModel.getPODMG()) ? sapDeliveryOrderModel.getPODMG()
								: "0");
				// 批次
				orderTemp.setBatch(
						!StringUtils.isNullOrEmpty(sapDeliveryOrderModel.getCHARG()) ? sapDeliveryOrderModel.getCHARG()
								: "");
				// 过账日期
				orderTemp.setPostDate(!StringUtils.isNullOrEmpty(sapDeliveryOrderModel.getWADAT_IST())
						? sapDeliveryOrderModel.getWADAT_IST()
						: "");
				// 发货状态
				orderTemp.setDeliveryStatus(
						!StringUtils.isNullOrEmpty(sapDeliveryOrderModel.getWBSTK()) ? sapDeliveryOrderModel.getWBSTK()
								: "");
				// 签收状态
				orderTemp.setSignStatus(
						!StringUtils.isNullOrEmpty(sapDeliveryOrderModel.getPDSTK()) ? sapDeliveryOrderModel.getPDSTK()
								: "");
				// 销售订单号
				orderTemp.setSaleOrderNo(!StringUtils.isNullOrEmpty(sapDeliveryOrderModel.getVBELN_S())
						? sapDeliveryOrderModel.getVBELN_S()
						: "");
				// 销售订单行行号
				orderTemp.setSaleOrderLineNo(!StringUtils.isNullOrEmpty(sapDeliveryOrderModel.getPOSNR_S())
						? sapDeliveryOrderModel.getPOSNR_S()
						: "");
				// 销售合同号
				orderTemp.setSaleContractNo(!StringUtils.isNullOrEmpty(sapDeliveryOrderModel.getVBELN_C())
						? sapDeliveryOrderModel.getVBELN_C()
						: "");
				// 合同名称
				orderTemp.setSaleContractName(
						!StringUtils.isNullOrEmpty(sapDeliveryOrderModel.getBSTKD()) ? sapDeliveryOrderModel.getBSTKD()
								: "");
				// 佣金
				orderTemp.setBrokerage(
						!StringUtils.isNullOrEmpty(sapDeliveryOrderModel.getYJZE()) ? sapDeliveryOrderModel.getYJZE()
								: "0");
				// 佣金货币
				orderTemp.setBrokerageCurreny(!StringUtils.isNullOrEmpty(sapDeliveryOrderModel.getYJZE_HB())
						? sapDeliveryOrderModel.getYJZE_HB()
						: "");
				// 佣金单价
				orderTemp.setBrokerageUnitPrice(
						!StringUtils.isNullOrEmpty(sapDeliveryOrderModel.getYJDJ()) ? sapDeliveryOrderModel.getYJDJ()
								: "0");
				// 佣金单价货币
				orderTemp.setBrokerageUnitPriceCurrent(sapDeliveryOrderModel.getYJDJ_HB());
				// 佣金供应商编码
				if (!StringUtils.isNullOrEmpty(sapDeliveryOrderModel.getYJLIFNR())) {
					orderTemp.setBrokerageSupplyCode(sapDeliveryOrderModel.getYJLIFNR());
					// 佣金供应商名称
					/*
					 * SupplyInfoModel supply =
					 * getSupplyInfoByInfCode(sapDeliveryOrderModel.getYJLIFNR()); if (null !=
					 * supply) { orderTemp.setBrokerageSupplyName(supply.getInfName()); }
					 */
				}

				// 该交货单佣金业务是否已完成
				orderTemp.setBrokerageEnd("0");
				// FOB港杂费
				orderTemp.setPortSurcharge(sapDeliveryOrderModel.getGZF());
				// FOB港杂费货币
				orderTemp.setPortSurchargeCurreny(sapDeliveryOrderModel.getGZF_HB());
				// FOB港杂供应商
				if (!StringUtils.isNullOrEmpty(sapDeliveryOrderModel.getGZLIFNR())) {
					orderTemp.setPortSurchargeSupply(sapDeliveryOrderModel.getGZLIFNR());
					// 供应商名称
					/*
					 * SupplyInfoModel supply =
					 * getSupplyInfoByInfCode(sapDeliveryOrderModel.getGZLIFNR()); if (null !=
					 * supply) { orderTemp.setPortSurchargeSupplyName(supply.getInfName()); }
					 */
				}
				// FOB港杂费业务是否完成
				orderTemp.setPortSurchargeEnd("0");
				// 保险费
				orderTemp.setPremium(sapDeliveryOrderModel.getBXF());
				// 保险费货币
				orderTemp.setPremiumCurreny(sapDeliveryOrderModel.getBXF_HB());
				// 保险费供应商
				if (!StringUtils.isNullOrEmpty(sapDeliveryOrderModel.getBXLIFNR())) {
					orderTemp.setPremiumSupply(sapDeliveryOrderModel.getBXLIFNR());
					// 供应商名称
					/*
					 * SupplyInfoModel supply =
					 * getSupplyInfoByInfCode(sapDeliveryOrderModel.getBXLIFNR()); if (null !=
					 * supply) { orderTemp.setPremiumSupplyName(supply.getInfName()); }
					 */
				}

				// 保险费业务是否完成
				orderTemp.setPremiumEnd("0");
				// 报关费
				orderTemp.setCustoms(sapDeliveryOrderModel.getBGF());
				// 报关费货币
				orderTemp.setCustomsCurreny(sapDeliveryOrderModel.getBGF_HB());
				// 报关费供应商

				if (!StringUtils.isNullOrEmpty(sapDeliveryOrderModel.getBGLIFNR())) {
					orderTemp.setCustomsSupply(sapDeliveryOrderModel.getBGLIFNR());
					// 供应商名称
					/*
					 * SupplyInfoModel supply =
					 * getSupplyInfoByInfCode(sapDeliveryOrderModel.getBGLIFNR()); if (null !=
					 * supply) { orderTemp.setCustomsSupplyName(supply.getInfName()); }
					 */
				}
				// 报关费业务是否完成
				orderTemp.setCustomsEnd("0");
				// 报检费
				orderTemp.setCostomsCensoringCharges(sapDeliveryOrderModel.getBJF());
				// 报检费货币
				orderTemp.setCostomsCensoringChargesCurreny(sapDeliveryOrderModel.getBJF_HB());
				// 报检费供应商

				if (!StringUtils.isNullOrEmpty(sapDeliveryOrderModel.getBJLIFNR())) {
					orderTemp.setCostomsCensoringChargesSupply(sapDeliveryOrderModel.getBJLIFNR());
					// 供应商名称
					/*
					 * SupplyInfoModel supply =
					 * getSupplyInfoByInfCode(sapDeliveryOrderModel.getBJLIFNR()); if (null !=
					 * supply) {
					 * orderTemp.setCostomsCensoringChargesSupplyName(supply.getInfName()); }
					 */
				}
				// 报检费业务是否完成
				orderTemp.setCostomsCensoringChargesEnd("0");
				// 检验费
				orderTemp.setSurveyFees(sapDeliveryOrderModel.getJYF());
				// 检验费货币
				orderTemp.setSurveyFeesCurreny(sapDeliveryOrderModel.getJYF_HB());
				// 检验费供应商

				if (!StringUtils.isNullOrEmpty(sapDeliveryOrderModel.getJYLIFNR())) {
					orderTemp.setSurveyFeesSupply(sapDeliveryOrderModel.getJYLIFNR());
					// 供应商名称
					/*
					 * SupplyInfoModel supply =
					 * getSupplyInfoByInfCode(sapDeliveryOrderModel.getJYLIFNR()); if (null !=
					 * supply) { orderTemp.setSurveyFeesSupplyName(supply.getInfName()); }
					 */
				}
				// 检验费业务是否完成
				orderTemp.setSurrveyFeesEnd("0");
				// 交货单状态
				orderTemp.setVBELNStatus(status);
				result += saleDeliveryOrdersDao.insert(orderTemp);

			} else {
				// 销售组织
				orderTemp.setVkorg(
						!StringUtils.isNullOrEmpty(sapDeliveryOrderModel.getVKORG()) ? sapDeliveryOrderModel.getVKORG()
								: "");
				// 交货单状态
				orderTemp.setVBELNStatus(status);
				// 判断是否更新费用字段
				// 佣金
				if (orderTemp.getBrokerageEnd().equals(Global.NO + "")) {
					orderTemp.setBrokerage(sapDeliveryOrderModel.getYJZE());
					orderTemp.setBrokerageCurreny(sapDeliveryOrderModel.getYJZE_HB());
					orderTemp.setBrokerageUnitPrice(sapDeliveryOrderModel.getYJDJ());
					orderTemp.setBrokerageUnitPriceCurrent(sapDeliveryOrderModel.getYJDJ_HB());
					if (!StringUtils.isNullOrEmpty(sapDeliveryOrderModel.getYJLIFNR())) {
						orderTemp.setBrokerageSupplyCode(sapDeliveryOrderModel.getYJLIFNR());
						// 佣金供应商名称
						SupplyInfoModel supply = getSupplyInfoByInfCode(sapDeliveryOrderModel.getYJLIFNR());
						if (null != supply) {
							orderTemp.setBrokerageSupplyName(supply.getInfName());
						}
					}
				}
				// FOB港杂费
				if (orderTemp.getPortSurchargeEnd().equals(Global.NO + "")) {
					orderTemp.setPortSurcharge(sapDeliveryOrderModel.getGZF());
					orderTemp.setPortSurchargeCurreny(sapDeliveryOrderModel.getGZF_HB());
					if (!StringUtils.isNullOrEmpty(sapDeliveryOrderModel.getGZLIFNR())) {
						orderTemp.setPortSurchargeSupply(sapDeliveryOrderModel.getGZLIFNR());
						// 供应商名称
						SupplyInfoModel supply = getSupplyInfoByInfCode(sapDeliveryOrderModel.getGZLIFNR());
						if (null != supply) {
							orderTemp.setPortSurchargeSupplyName(supply.getInfName());
						}
					}
				}
				// 保险费
				if (orderTemp.getPremiumEnd().equals(Global.NO + "")) {
					orderTemp.setPremium(sapDeliveryOrderModel.getBXF());
					orderTemp.setPremiumCurreny(sapDeliveryOrderModel.getBXF_HB());
					if (!StringUtils.isNullOrEmpty(sapDeliveryOrderModel.getBXLIFNR())) {
						orderTemp.setPremiumSupply(sapDeliveryOrderModel.getBXLIFNR());
						// 供应商名称
						SupplyInfoModel supply = getSupplyInfoByInfCode(sapDeliveryOrderModel.getBXLIFNR());
						if (null != supply) {
							orderTemp.setPremiumSupplyName(supply.getInfName());
						}
					}

				}
				// 报关费
				if (orderTemp.getCustomsEnd().equals(Global.NO + "")) {
					orderTemp.setCustoms(sapDeliveryOrderModel.getBGF());
					orderTemp.setCustomsCurreny(sapDeliveryOrderModel.getBGF_HB());
					if (!StringUtils.isNullOrEmpty(sapDeliveryOrderModel.getBGLIFNR())) {
						orderTemp.setCustomsSupply(sapDeliveryOrderModel.getBGLIFNR());
						// 供应商名称
						SupplyInfoModel supply = getSupplyInfoByInfCode(sapDeliveryOrderModel.getBGLIFNR());
						if (null != supply) {
							orderTemp.setCustomsSupplyName(supply.getInfName());
						}
					}

				}
				// 报检费
				if (orderTemp.getCostomsCensoringCharges().equals(Global.NO + "")) {
					orderTemp.setCostomsCensoringCharges(sapDeliveryOrderModel.getBJF());
					orderTemp.setCostomsCensoringChargesCurreny(sapDeliveryOrderModel.getBJF_HB());
					if (!StringUtils.isNullOrEmpty(sapDeliveryOrderModel.getBJLIFNR())) {
						orderTemp.setCostomsCensoringChargesSupply(sapDeliveryOrderModel.getBJLIFNR());
						// 供应商名称
						SupplyInfoModel supply = getSupplyInfoByInfCode(sapDeliveryOrderModel.getBJLIFNR());
						if (null != supply) {
							orderTemp.setCostomsCensoringChargesSupplyName(supply.getInfName());
						}
					}

				}
				// 检验费
				if (orderTemp.getSurrveyFeesEnd().equals(Global.NO + "")) {
					orderTemp.setSurveyFees(sapDeliveryOrderModel.getJYF());
					orderTemp.setSurveyFeesCurreny(sapDeliveryOrderModel.getJYF_HB());
					if (!StringUtils.isNullOrEmpty(sapDeliveryOrderModel.getJYLIFNR())) {
						orderTemp.setSurveyFeesSupply(sapDeliveryOrderModel.getJYLIFNR());
						// 供应商名称
						SupplyInfoModel supply = getSupplyInfoByInfCode(sapDeliveryOrderModel.getJYLIFNR());
						if (null != supply) {
							orderTemp.setSurveyFeesSupplyName(supply.getInfName());
						}
					}
				}
				result += saleDeliveryOrdersDao.update(orderTemp);
			}
		}
		if (result < 1) {
			return HttpResult.error("交货单信息传输错误");
		}
		return HttpResult.ok();
	}

	private SupplyInfoModel getSupplyInfoByInfCode(String code) {
		List<SupplyInfoModel> supplys = infoMapper.loadListByInfCode(code);
		if (!CollectionUtils.isEmpty(supplys)) {
			SupplyInfoModel supply = supplys.get(0);
			return supply;
		}
		return null;
	}

}
